package com.my.main.controller.userAndRight;


import com.my.main.base.controller.BaseController;
import com.my.main.base.entity.Result;
import com.my.main.base.entity.ResultCode;
import com.my.main.entity.userAndRight.SysDepartment;
import com.my.main.service.userAndRight.SysDepartmentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 组织管理
 *
 * @author mengft 2020-05-06
 */


@CrossOrigin
@RequestMapping(value="/api/v1/userAndRight/sysDepartment")
@RestController
public class DepartmentManageController extends BaseController {


    @Autowired
    private SysDepartmentService sysDepartmentService;


    /**
     * 部门管理 | 新增或修改
     *
     * @param sysDepartment
     *
     * @author mengft 2020-05-09
     */
    @ApiOperation(value="用户与权限 - 新增或修改组织部门")
    @RequestMapping(value="/updateDepartment", method = RequestMethod.POST)
    public Result updateDepartment(@RequestBody SysDepartment sysDepartment) {
        if (sysDepartment == null) {
            return new Result(ResultCode.FAIL);
        }

        try {
            // 修改
            if (sysDepartment.getDepartmentId()!=null && !StringUtils.isEmpty(sysDepartment.getDepartmentId())) {
                if (sysDepartment.getDepartmentId().equals(sysDepartment.getPid())) {
                    return new Result(ResultCode.FAIL, "上级部门不能为本部门");
                }
                // 查询修改的数据是否存在
                SysDepartment sysDepartmentOld = sysDepartmentService.queryByUuid(sysDepartment.getDepartmentId());
                if (sysDepartmentOld == null) {
                    return new Result(ResultCode.FAIL, "未找到该部门，请稍后重试...");
                }

                sysDepartmentOld.setPid(sysDepartment.getPid());
                sysDepartmentOld.setName(sysDepartment.getName());
                sysDepartmentOld.setSort(sysDepartment.getSort());
                sysDepartmentOld.setLastEditIp(requestUtil.getIp());
                sysDepartmentOld.setLastEditBy(userInfo.getUserId());
                sysDepartmentOld.setAddTime(null);
                sysDepartmentOld.setLastEditTime(null);
                sysDepartmentService.isUpdate(sysDepartmentOld);
            }

            // 新增
            if (sysDepartment.getDepartmentId()==null || StringUtils.isEmpty(sysDepartment.getDepartmentId())) {
                sysDepartment.setDepartmentId(idWorker.nextId() + "");
                sysDepartment.setAddIp(requestUtil.getIp());
                sysDepartment.setAddUserId(userInfo.getUserId());
                sysDepartment.setLastEditIp(requestUtil.getIp());
                sysDepartment.setLastEditBy(userInfo.getUserId());
                sysDepartment.setIsDel(false);
                sysDepartmentService.isSave(sysDepartment);
            }

            return new Result(ResultCode.SUCCESS);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }
    }


    /**
     * 部门管理 | 查询
     *
     * @param map{departmentId: 部门id}
     *
     * @author mengft 2020-05-09
     */
    @ApiOperation(value="用户与权限 - 查询组织部门")
    @RequestMapping(value="/queryDepartment", method = RequestMethod.POST)
    public Result queryDepartment(@RequestBody Map<String, String> map) {
        Map<String, Object> resMap = new HashMap<>();
        if (map==null || map.get("departmentId")==null) {
            return new Result(ResultCode.FAIL, "系统繁忙，请稍后...");
        }

        try {
            SysDepartment sysDepartment = sysDepartmentService.queryByUuid(map.get("departmentId"));
            if (sysDepartment == null) {
                return new Result(ResultCode.FAIL, "未找到该部门，请重试...");
            }

            resMap.put("departmentId", sysDepartment.getDepartmentId());
            resMap.put("pid", sysDepartment.getPid());
            resMap.put("name", sysDepartment.getName());
            resMap.put("sort", sysDepartment.getSort());

            return new Result(ResultCode.SUCCESS, resMap);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL, "系统繁忙，请稍后...");
        }
    }


    /**
     * 查询部门列表
     *
     * @param map （page：页数， limit： 每页条数， name： 部门名称， pids： 需查看子级部门id）
     *
     * @author mengft 2020-05-09
     */
    @ApiOperation(value="用户与权限 - 查询组织部门列表", tags = NOINTERCEPT)
    @RequestMapping(value="/queryDepartmentList",method = RequestMethod.POST)
    public Result queryDepartmentList(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> paramMap = new HashMap<>();
//        if (map.get("page")==null || map.get("limit")==null) {
//            return new Result(ResultCode.FAIL);
//        }

//        if (map.get("multistep")==null) {
//            paramMap.put("multistep", false);
//        }

//        Long count = 0L;
        try {
            // 组织名称
            if (map.get("name")!=null && !"".equals(map.get("name"))) {
                paramMap.put("name", map.get("name"));
            }

//            paramMap.put("page", (Integer.valueOf(map.get("page")) - 1) * Integer.valueOf(map.get("limit")));
//            paramMap.put("limit", Integer.valueOf(map.get("limit")));

//            if (map.get("pids") != null) {
//                paramMap.put("pids", map.get("pids") + ",0");
//            } else {
//                paramMap.put("pids", 0L);
//            }

            if (map.get("pid")==null) {
                paramMap.put("pid", "0");
            } else {
                paramMap.put("pid", map.get("pid"));
            }
            List<SysDepartment> sysDepartments = sysDepartmentService.queryList(paramMap);
//            count = sysDepartmentService.queryCount(paramMap);

            List<Map<String, Object>> sysDepartmentList = new ArrayList<>();
            for(SysDepartment sysDepartment: sysDepartments) {
                Map<String, Object> sysDepartmentMap = new HashMap<>();
                sysDepartmentMap.put("departmentId", sysDepartment.getDepartmentId());
                sysDepartmentMap.put("pid", sysDepartment.getPid());
                sysDepartmentMap.put("name", sysDepartment.getName());
                sysDepartmentMap.put("sort", sysDepartment.getSort());
                sysDepartmentMap.put("lastEditTime", sysDepartment.getLastEditTime());

                if (map.get("multistep")!=null && (Boolean)map.get("multistep")) {
                    List<Map<String,Object>> children = queryChildDepList(sysDepartment.getDepartmentId());
                    if (children.size() > 0) {
                        sysDepartmentMap.put("children", children);
                    }
                }
                sysDepartmentList.add(sysDepartmentMap);
            }
            resMap.put("sysDepartmentList", sysDepartmentList);
//            resMap.put("totalCount", count);
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }
    }


    /**
     * 删除部门
     *
     * @param map（departmentId： id）
     *
     * @authod mengft 2020-05-09
     */
    @ApiOperation(value="用户与权限 - 删除组织部门")
    @RequestMapping(value="/delDepartment",method = RequestMethod.POST)
    public Result delDepartment(@RequestBody Map<String, String> map) {
        if (map.get("departmentId") == null) {
            return new Result(ResultCode.FAIL);
        }
        if (map.get("departmentId").equals("8888") || map.get("departmentId").equals("888801")) {
            return new Result(ResultCode.FAIL, "不允许删除默认分组");
        }

        try {
            // 查询部门是否存在
            SysDepartment sysDepartment = sysDepartmentService.queryByUuid(map.get("departmentId"));
            if (sysDepartment == null) {
                return new Result(ResultCode.FAIL);
            }

            sysDepartmentService.isDeleteByUuid(sysDepartment.getDepartmentId());
            return new Result(ResultCode.SUCCESS);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }

    }


    /**
     * 查询子级部门
     *
     * @author mengft 2020-05-09
     */
    private List<Map<String,Object>> queryChildDepList(String pid) {
        Map<String,Object> resMap = new HashMap<String,Object>();
        List<Map<String, Object>> sysDepartmentList = new ArrayList<>();

        try {
            // 放入查询条件
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("pid", pid);
            List<SysDepartment> sysDepartments = sysDepartmentService.queryParentList(paramMap);

            for (SysDepartment sysDepartment : sysDepartments) {
                Map<String,Object> sysDepartmentMap = new LinkedHashMap<String,Object>();

                sysDepartmentMap.put("departmentId", sysDepartment.getDepartmentId());
                sysDepartmentMap.put("pid", sysDepartment.getPid());
                sysDepartmentMap.put("name", sysDepartment.getName());
                sysDepartmentMap.put("sort", sysDepartment.getSort());
                sysDepartmentMap.put("lastEditTime", sysDepartment.getLastEditTime());

                // 递归查询子部门
                List<Map<String,Object>> children = new ArrayList<Map<String,Object>>();
                children = queryChildDepList(sysDepartment.getDepartmentId());
                if (children.size() > 0) {
                    sysDepartmentMap.put("children", children);
                }

                sysDepartmentList.add(sysDepartmentMap);
            }

            //返回参数
            return sysDepartmentList;
        } catch (Exception e) {
            e.printStackTrace();
            return sysDepartmentList;
        }
    }

}
